from logs.Logger import Logger
import file_md5.FilePrint as file_print
import time
import sys
import os
import requests
from crawler.db.ImageInfoDBOperator import DBOperator, ImageInfo

# 日志初始化
log = Logger("D:/workspace/logs/crawler.log", level='info')

class ImageDownloader:

    def image_downloader(self, item, title, path, date):
        """

        :param item: 待下载图片地址
        :param title: 下载后文件地址
        :param path: 存放路径
        :param date: 日期
        :return: 
        """
        res = requests.get(item)
        print(item)
        title = self.path_clean(title)
        tmp_dir = path + date + '/'
        print(tmp_dir)
        self.mkdir(tmp_dir)
        download_file_name = tmp_dir + title + self.file_extension(item)
        with open(download_file_name, 'wb') as f:
            f.write(res.content)
            f.close()
        return download_file_name
    def image_downloader1(self, item, title, path, date, extension):
        """
        :param item: 待下载图片地址
        :param title: 下载后文件地址
        :param path: 存放路径
        :param date: 日期
        :param extension: 扩展名
        :return:
        """
        res = requests.get(item)
        print(item)
        title = self.path_clean(title)
        tmp_dir = path + date + '/'
        print(tmp_dir)
        self.mkdir(tmp_dir)
        download_file_name = tmp_dir + title + extension
        with open(download_file_name, 'wb') as f:
            f.write(res.content)
            f.close()
        return download_file_name
    def path_clean(self, path):
        path = path.replace('?', '').replace("<", "").replace(">", "").replace(":", "")
        return path

    def mkdir(self, path):
        # 引入模块
        import os

        # 去除首位空格
        path = path.strip()
        # 去除尾部 \ 符号
        path = path.rstrip("\\")

        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists = os.path.exists(path)

        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path)

            print
            path + ' 创建成功'
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            print
            path + ' 目录已存在'
            return False

    def file_extension(self, path):
      return os.path.splitext(path)[1]

